<?php
namespace app\home\controller;

// 引用验证码
use think\captcha\Captcha;
// 引用tp的基础控制器
use think\Controller;
use think\Db;
use think\Request;

class Index extends Controller
{
    public function __construct()
    {
        // 手动继承父级
        parent::__construct();

        $this->UserModel = model('User.User');

        $this->RecordModel = model('User.Record');

        $this->PostModel = model('Post.Post');

        // 获取用户表所有数据
        $UserList = model('User.User')->column('id,salt');

        // 获取cookie的数据
        $LoginUser = cookie('LoginUser') ? cookie('LoginUser') : '';

        // 存放id的字符串
        $userid = 0;

        foreach($UserList as $key => $value)
        {
            $UserSalt = md5($key.$value);

            if($LoginUser == $UserSalt)
            {
                $userid = $key;
                break;
            }
        }

        // 根据id去查询用户表 对象 => 数组 > toArray()
        $User = model('User.User')->find($userid);
        // $User = Db::table('pre_user')->find($userid);

        $userid = isset($User['id']) ? $User['id'] : 0;

        // 消费记录表
        $sing = $this->RecordModel->whereTime('createtime','today')->where(['userid' => $userid,'state' => 4])->find();

        if($sing)
        {
            $User['sing'] = 1;
        }
        
        $User = $User ? $User : [];

        // 把用户数据给继承home公共控制器的子控制器
        $this->LoginUser = $User;
        

        // 赋值视图
        $this->assign([
            'LoginUser' => $User
        ]);
    }

    public function index()
    {
        // 接收分类id => 帖子 => 根据分类id去查询相应帖子
        $cateid = $this->request->param('cateid','');

        // 帖子状态
        $state = $this->request->param('state','');

        // 采纳
        $accept = $this->request->param('accept',0);

        // 关键字
        $keyword = $this->request->param('keyword','');
        
        // 条件数组
        $where = [];

        if(!empty($cateid))
        {
            
            $where['cateid'] = $cateid;
        }

        if(!empty($state))
        {
            $where['state'] = $state;
        }

        if($accept == 0)
        {
            // where `accept` is null
            $where['accept'] = ['exp',Db::raw('is null')];
        }elseif($accept == 1)
        {
            $where['accept'] = ['exp',Db::raw('is not null')];
        }

        if(!empty($keyword))
        {
            $where['title'] = ['like',"%$keyword%"];
        }

        $CateList = model('Post.Cate')->order('weigh','desc')->limit(7)->select();

        // 查询签到积分
        $SignPoint = model('config')->where('key','SignPoint')->value('value');

        $PostList = model('Post.Post')->with(['user','cate'])->where($where)->order('post.createtime','desc')->paginate(1,false,['query' => Request::instance()->param()]);
        
        $HotList = model('Post.Comment')->with(['post'])->field("COUNT(*) as num,post.title,post.id")->whereTime('comment.createtime', 'week')->order('num desc')->group('comment.postid')->limit(5)->select();
        
        
        return $this->fetch('',[
            'CateList' => $CateList,
            'cateid' => $cateid,
            'PostList' => $PostList,
            'SignPoint' => $SignPoint,
            'state' => $state,
            'accept' => $accept,
            'HotList' => $HotList
        ]);
    }

    // 帖子详情
    public function info()
    {
        $postid = $this->request->param('postid',0);

        $post = $this->PostModel->with(['user','cate'])->where('post.id',$postid)->find();

        if(!$post)
        {
            $this->error('帖子不存在，请重新选择');
        }

        // 浏览量按id进行更新
        $userid = !empty($this->LoginUser['id']) ? $this->LoginUser['id'] : 0;

        $User = $this->UserModel->find($userid);

        // 字符串转数组
        $VisitArr = explode(',',$post['visit']);

        if($User)
        {
            

            if(!in_array($User['id'],$VisitArr))
            {
                $VisitArr[] = $User['id'];

                $VisitStr = implode(',',$VisitArr);
                // 把字符串的左边逗号去掉
                $VisitStr = ltrim($VisitStr,',');

                $this->PostModel->where('id',$postid)->update(['visit' => $VisitStr]);

            }

        }

        $VisitCount = !empty($VisitArr) ? count($VisitArr) : 1;

        // 查询该帖子是否被当前登录用户收藏
        $collect = model('User.Collect')->where(['userid' => $userid,'postid' => $postid])->value('userid');

        // 查询评论数据
        $CommentList = model('Post.Comment')->with('user')->where('postid',$postid)->order('comment.createtime')->select();

        $CommentList = CommentTree($CommentList,0,$User);

        return $this->fetch('',[
            'post' => $post,
            'VisitCount' => $VisitCount,
            'collect' => $collect,
            'userid' => $userid,
            'CommentList' => $CommentList
        ]);
    }

    // 登录
    public function login()
    {
        if($this->request->isPost())
        {
            $params = $this->request->param();

            if(!captcha_check($params['vercode']))
            {
                $this->error('验证码错误');
            }

            // 通过邮箱去查询数据库是否存在该用户
            $User = $this->UserModel->where(['email' => $params['email']])->find();

            // 查询出来的结果为空 说明该用户不存在
            if(!$User)
            {
                $this->error('该用户不存在');
            }

            $password = md5($params['pass'].$User['salt']);

            if($password != $User['password'])
            {
                $this->error('密码错误');
            }

            // 设置cookie
            // $data = [
            //     'id' => $User['id'],
            //     'email' => $User['email'],
            //     'nickname' => $User['nickname'],
            //     'vip' => $User['vip'],
            //     'auth' => $User['auth'],
            //     'sex_text' => $User['sex_text'],
            //     'sex' => $User['sex'],
            //     'point' => $User['point'],
            
            // ];

            // cookie的值只要你不更新它就不更新

            $data = md5($User['id'].$User['salt']);

            cookie('LoginUser',$data);

            $this->success('登录成功',url('home/user/index'));
        }
        return $this->fetch();
    }

    // 注册
    public function register()
    {
        // 判断这是否post请求
        if($this->request->isPost())
        {
            // get post 接收全部参数
            $params = $this->request->param();

            // 验证验证码
            if(!captcha_check($params['vercode']))
            {
                // 跳转中间页
                $this->error('验证码错误');
            }

            // 判断密码和确认密码是否一致
            if($params['pass'] != $params['repass'])
            {
                $this->error('密码与确认密码不一致');
            }

            // 生成密码盐
            $salt = build_ranstr();
            
            // 进行加密
            $password = md5($params['pass'].$salt);

            // Db类或者模型增删改查 用Db类查询注册的赠送积分
            $point = Db::name('config')->where('key','RegisterPoint')->value('value');

            // 封装插入数据库的数组
            $data = [
                'email' => $params['email'],
                'nickname' => $params['nickname'],
                'password' => $password,
                'salt' => $salt,
                'sex' => 0,
                'auth' => 0,
                'vip' => 1,
                'point' => $point
            ];

            $result = $this->UserModel->validate('common/User/User')->save($data);

            if($result === FALSE)
            {
                $this->error($this->UserModel->getError());
            }else{
                $this->success('注册成功',url('home/index/login'));
            }

        }
        // 输出视图
        return $this->fetch();
    }



    // 签到
    public function sign()
    {
        if($this->request->isAjax())
        {
            if(empty($this->LoginUser))
            {
                $this->error('请先登录');
            }

            // 查询今天是否签到
            $sing = $this->RecordModel->whereTime('createtime','today')->where(['userid' => $this->LoginUser['id'],'state' => 4])->find();

            if($sing)
            {
                $this->error('您已签到了');
            }

            /* 
                消费记录表 新增一条记录
                用户表 更新积分
            */

            // 开启事务
            $this->UserModel->startTrans();
            $this->RecordModel->startTrans();

            // 获取到签到的积分
            $SignPoint = model('config')->where(['key' => 'SignPoint'])->value('value');

            // 用户的积分加上签到的积分
            $Point = bcadd($this->LoginUser['point'],$SignPoint);

            // 更新数据
            $UserData = [
                'id' => $this->LoginUser['id'],
                'point' => $Point
            ];

            $UserStatus = $this->UserModel->isUpdate(true)->save($UserData);

            if($UserStatus === FALSE)
            {
                $this->error('签到失败');
            }

            // 消费记录
            $RecordData = [
                'userid' => $this->LoginUser['id'],
                'point' => $SignPoint,
                'content' => "您在".date('Y-m-d H:i',time())."通过【签到】获取了{$SignPoint}积分",
                'state' => 4
            ];

            $RecordStatus = $this->RecordModel->validate('common/User/Record')->save($RecordData);

            if($RecordStatus === FALSE)
            {
                $this->UserModel->rollback();
                $this->error($this->RecordModel->getError());
            }

            if($UserStatus === FALSE || $RecordStatus === FALSE)
            {
                $this->UserModel->rollback();
                $this->RecordModel->rollback();
                $this->error('签到失败');
            }else{
                $this->UserModel->commit();
                $this->RecordModel->commit();
                $this->success('签到成功');
            }

        }
    }

    // 验证邮箱
    public function auth()
    {
        $email = $this->request->param('email');

        $UserList = $this->UserModel->column('email,salt');

        // 定义字符串
        $UserEmail = '';

        foreach($UserList as $key => $value)
        {
            $userSalt = md5($key.$value);

            if($email == $userSalt)
            {
                $UserEmail = $key;
                break;
            }
        }

        $User = $this->UserModel->where('email',$UserEmail)->find();

        if(!$User)
        {
            $this->error('无效邮箱');
        }

        $data = [
            'id' => $User['id'],
            'auth' => 1
        ];

        // isUpdate(true) => 更新操作
        $result = $this->UserModel->isUpdate(true)->save($data);

        if($result === FALSE)
        {
            $this->error('认证失败');
        }else{
            cookie('LoginUser',md5($User['id'].$User['salt']));
            $this->success('认证成功',url('home/user/index'));
        }
    }

    // 验证码
    public function vercode()
    {
        $config = [
            'length' => 1,
            'fontSize' => 20,
            'imageW' => 150,
            'imageH' => 40,
            'codeSet' => '0123456789'
        ];
        //将$config的值作为引入到Capcha类中
        $captcha = new Captcha($config);
        // 使用Captcha中生成图片方法并返回值
        return $captcha->entry();
    }
}